//
//  AppDelegate.m
//  WubiTest
//
//  Created by MingmingSun on 2019/12/6.
//  Copyright © 2019 Sunmingming. All rights reserved.
//

#import "AppDelegate.h"

@interface AppDelegate ()<DNSInAppPurchaseManagerDelegate>

@property(nonatomic,assign) BOOL enableIAP;

@end

@implementation AppDelegate

@synthesize storePayStatus;


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
	// Override point for customization after application launch.
	self.enableIAP = YES;
	
	self.storePayStatus = EStoreNotReached;
	self.myNowAppId = kIAPOpenLevel;
	self.iapManager = [[DNSInAppPurchaseManager alloc] init];
	self.iapManager.delegate = self;
	[self setupStore];
	
	self.mydefaults = [NSUserDefaults standardUserDefaults];
	if([self.mydefaults integerForKey:@"spid"] == 0) {
		[self.mydefaults setInteger:1 forKey:@"spid"];
		[self.mydefaults setInteger:1 forKey:@"nowLevel"];
		[self.mydefaults setBool:false forKey:@"hasBoughtLevel"];
	}
	return YES;
}


#pragma mark - UISceneSession lifecycle


- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options {
	// Called when a new scene session is being created.
	// Use this method to select a configuration to create the new scene with.
	return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
}

#pragma mark - In-App Purchase setup
-(void)setupStore
{
    if ([self.iapManager canMakePurchases]) {
        NSLog(@"-----------can pay--------------");
        
        //Run on background thread - delegate forces callbacks on main thread.
        NSOperationQueue *background = [[NSOperationQueue alloc] init];
        __block DNSInAppPurchaseManager *blockManager = self.iapManager;
        [background addOperationWithBlock:^{
            //Gets your store items.
            [blockManager loadStoreWithIdentifiers:[NSSet setWithObjects:kIAPOpenLevel,nil]];
        }];
    } else {
        NSLog(@"-----------cannot pay--------------");
    }
}

-(void)startToRestore:(NSString*)aIAP {
    if(!self.enableIAP){
        [self.myIAPDelegate VCIAPSucceed:NULL];
        return;
    }
    if(storePayStatus == EStoreNotReached){
        [self.myIAPDelegate VCIAPFailed:@"正在连接支付系统，请稍后再试。"];
        return;
    }
    if(storePayStatus == EStoreCanNotPay){
        [self.myIAPDelegate VCIAPFailed:@"获取支付详情失败，请检查网络后重启软件。"];
        return;
    }
    if(storePayStatus == EStoreReachFailed){
        [self.myIAPDelegate VCIAPFailed:@"连接支付系统失败，请检查网络后重启软件。"];
        return;
    }
    if(storePayStatus != EStoreCanPay)
        return;
    typeof(self) __weak weakSelf = self;
    NSOperationQueue *background = [[NSOperationQueue alloc] init];
    [background addOperationWithBlock:^{
        [weakSelf.iapManager restoreExistingPurchases];
    }];
}

-(void)startToIAP:(NSString*)aIAP{
    if(!self.enableIAP){
        [self.myIAPDelegate VCIAPSucceed:aIAP];
        return;
    }
    if(storePayStatus == EStoreNotReached){
        [self.myIAPDelegate VCIAPFailed:@"正在连接支付系统，请稍后再试。"];
        return;
    }
    if(storePayStatus == EStoreCanNotPay){
        [self.myIAPDelegate VCIAPFailed:@"获取支付详情失败，请检查网络后重启软件。"];
        return;
    }
    if(storePayStatus == EStoreReachFailed){
        [self.myIAPDelegate VCIAPFailed:@"连接支付系统失败，请检查网络后重启软件。"];
        return;
    }
    if(storePayStatus != EStoreCanPay)
        return;
    BOOL findProduct = NO;
    for (SKProduct *cacheProduct in self.availableProducts) {
        if([cacheProduct.productIdentifier isEqualToString:aIAP]){
            findProduct = YES;
            self.myNowAppId = cacheProduct.productIdentifier;
            
            typeof(self) __weak weakSelf = self;
            NSOperationQueue *background = [[NSOperationQueue alloc] init];
            [background addOperationWithBlock:^{
                [weakSelf.iapManager purchaseProduct:cacheProduct];
            }];
            break;
        }
    }
    if(!findProduct){
        [self.myIAPDelegate VCIAPFailed:@"未查询到该商品信息，请确保软件为正版。"];
        return;
    }
}

#pragma mark - In App Purchase Manager Delegate
-(void)productRetrievalFailed:(NSString *)errorMessage
{
    self.storePayStatus = EStoreReachFailed;
    NSLog(@"get store failed");
}

-(void)productsRetrieved:(NSArray *)products
{
    NSLog(@"--retrieved--");
    if (products) {
        self.availableProducts = products;
        if(products.count)
        {
            self.storePayStatus = EStoreCanPay;
        }
        else
        {
            self.storePayStatus = EStoreReachFailed;
        }
    } else {
        self.storePayStatus = EStoreCanNotPay;
    }
}

-(void)purchaseFailed:(NSString *)errorMessage
{
    NSLog(@"--failed-- %@",errorMessage);
    [self.myIAPDelegate VCIAPFailed:[NSString stringWithFormat:@"支付失败：%@",errorMessage]];
}

-(void)purchaseCancelled
{
    NSLog(@"--cancelled--");
    [self.myIAPDelegate VCIAPFailed:@"取消支付。"];
}

-(void)purchaseSucceeded:(NSString *)productIdentifier
{
    NSLog(@"--succeed-- %@",productIdentifier);
    if(!productIdentifier.length)
    {
        [self.myIAPDelegate VCIAPFailed:@"支付失败，支付参数错误。"];
        return;
    }
    [self.myIAPDelegate VCIAPSucceed:productIdentifier];
}

-(void)restorationSucceeded
{
    NSLog(@"--restore succeed--");
    //not used
    [self.myIAPDelegate VCIAPSucceed:@"restored"];
}

-(void)restorationFailedWithError:(NSString *)errorMessage
{
    NSLog(@"--restore failed-- %@",errorMessage);
    //  not used;
    [self.myIAPDelegate VCIAPFailed:@"恢复购买失败。"];
}


@end
